<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.vat_id ? 'VAT资料' : '添加VAT资料'" v-model="visible" align-center width="1200px"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <div class="grid grid-cols-3 gap-x-3">
        <el-form-item label="VAT税号" class="col-span-2">
          <el-input v-model.lazy="form.vat_num" placeholder="请输入" :maxlength="250" show-word-limit />
        </el-form-item>
        <el-form-item label="VAT证书日期">
          <el-date-picker v-model="form.vat_certificate_date" placeholder="日期选择" type="date" value-format="YYYY-MM-DD"
            class="w-full" />
        </el-form-item>
        <el-form-item label="德国本地税号" class="col-span-2">
          <el-input v-model.lazy="form.german_local_tax_num" placeholder="请输入" :maxlength="250" show-word-limit />
        </el-form-item>
        <el-form-item label="德国本地日期">
          <el-date-picker v-model="form.german_local_date" placeholder="日期选择" type="date" value-format="YYYY-MM-DD"
            class="w-full" />
        </el-form-item>
        <el-form-item label="所在国VAT" prop="vat_country" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.vat_country" :options="options.vat_country" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="公司" prop="company_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.company_id" :options="options.company" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="业务负责人" prop="business_owner_id"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VCascader v-model="form.business_owner_id" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="提交申请时间" prop="submit_apply_date">
          <el-date-picker v-model="form.submit_apply_date" placeholder="日期选择" type="date" value-format="YYYY-MM-DD"
            class="w-full" />
        </el-form-item>
        <el-form-item label="VAT证书">
          <ImageUpload v-model="form.vat_certificate_file" :isShowTip="false" width="60px" height="60px" :limit="1"
                       :fileSize="200"
            :fileType="['jpg', 'png', 'jpeg', 'gif', 'pdf']" />
        </el-form-item>
        <el-form-item label="VAT绑定店铺" class="col-span-full">
          <vxe-table :data="form.bind_shops" class="w-full">
            <vxe-column title="平台" field="platform_name" minWidth="200"></vxe-column>
            <vxe-column title="店铺" field="shop_name" minWidth="150"></vxe-column>
            <vxe-column title="对接业务员" field="preferred_saleman_name" minWidth="eu_eori_num">
              <template #default="{ row, rowIndex }">
                <VCascader @change="v => handleSaleman(v, rowIndex)" v-model="row.docking_salesman_id" placeholder="请选择" class="w-full" />
              </template>
            </vxe-column>
            <vxe-column title="组织" field="first_level_department" minWidth="100"></vxe-column>
            <vxe-column title="操作" width="100">
              <template #default="{ rowIndex }">
                <el-button link type="primary" @click="form.bind_shops.splice(rowIndex, 1)">移除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
          <div class="border border-[var(--base-border-color)] flex w-full px-3 py-2 border-t-0">
            <el-cascader
              :options="(options.platform_shop || []).map(d => ({ shop_id: d.platform_id, shop_name: d.platform_name, children: d.shops.filter(d => !form.bind_shops.some(s => s.shop_id === d.shop_id)) }))"
              v-model="form.bind_ids" clearable filterable :props="{ label: 'shop_name', value: 'shop_id' }" class="w-60"
              @change="shopChange">
            </el-cascader>
            <el-button type="primary" plain class="ml-2" :disabled="!form.bind_ids.length"
              @click="form.bind_shops.push(form.bind_info) && (form.bind_info = {}) && (form.bind_ids = [])">添加</el-button>
          </div>
        </el-form-item>
        <el-form-item label="欧盟EORI Number">
          <el-input v-model.lazy="form.eu_eori_num" placeholder="请输入" :maxlength="250" show-word-limit />
        </el-form-item>
        <el-form-item label="欧盟EORI生效日期">
          <el-date-picker v-model="form.eu_eori_effective_date" placeholder="日期选择" type="date" value-format="YYYY-MM-DD"
            class="w-full" />
        </el-form-item>
        <el-form-item label="英国EORI Number">
          <el-input v-model.lazy="form.en_eori_num" placeholder="请输入" :maxlength="250" show-word-limit />
        </el-form-item>
        <el-form-item label="英国EORI生效日期">
          <el-date-picker v-model="form.en_eori_effective_date" placeholder="日期选择" type="date" value-format="YYYY-MM-DD"
                          class="w-full" />
        </el-form-item>
        <el-form-item label="现合作服务商" prop="now_service_provider"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input v-model.lazy="form.now_service_provider" placeholder="请输入" :maxlength="250" show-word-limit />
        </el-form-item>
        <el-form-item label="合作时间" prop="now_cooperate_date">
          <el-date-picker v-model="form.now_cooperate_date" placeholder="日期选择" type="date"
            value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
        <el-form-item label="历史合作服务商">
          <el-input v-model.lazy="form.history_service_provider" placeholder="请输入" :maxlength="250" show-word-limit />
        </el-form-item>
        <el-form-item label="历史合作时间" prop="switch_service_provider_date">
          <el-date-picker v-model="form.history_cooperate_date" placeholder="日期选择" type="date"
                          value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
        <el-form-item label="申报周期" prop="reporting_period"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.reporting_period" :options="options.reporting_period" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="存续周期" prop="existence_period"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.existence_period" :options="options.existence_period" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="(d, i) in options.status" :key="i" :label="d.value">{{ d.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入"
            :maxlength="800" show-word-limit />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import ImageUpload from './ImageUpload/index.vue'
import SimpleTable from './SimpleTable/index.vue'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const success = ref(false)
let loadings = reactive({})

const shopChange = (val = []) => {
  const [platform, shop_id] = val
  api.shopInfo({ shop_id }).then(res => {
    form.value.bind_info = res.data
    if (!form.value.bind_info.docking_salesman_id) form.value.bind_info.docking_salesman_id = form.value.bind_info.preferred_saleman_id
  })
}

// 表单处理
const formRef = ref()
const form = ref({})

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  // 编辑
  if (id) {
    const res = await api.detail({ vat_id: id })
    form.value = res.data
  } else { //新增
    form.value = {
      "vat_num": "",
      "vat_certificate_date": "",
      "german_local_tax_num": "",
      "german_local_date": "",
      "vat_country": '',
      "company_id": '',
      "business_owner_id": '',
      "submit_apply_date": "",
      "vat_certificate_file": [],
      "eu_eori_num": "",
      "eori_effective_date": "",
      "service_provider": "",
      "switch_service_provider": '',
      "switch_service_provider_date": "",
      "reporting_period": '',
      "existence_period": '',
      "status": 1,
      "remark": "",
      "bind_shops": [],
    }
    formRef?.value?.resetFields()
  }
  form.value.bind_ids = []
  form.value.bind_info = {}
  loadings = reactive({})
  success.value = false
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}

const handleSaleman = ({value}, index) => {
  form.value.bind_shops[index].docking_salesman_id = value
}

// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  api[form.value.vat_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    success.value = true
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>